package helpers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class StringHelper {
	public static String cutString(String description, int count) {
		String[] str = description.split(" ");
		int max = str.length;
		if (max >= count) {
			max = count;
		}
		description = "";
		
		for (int i = 0; i < max; i++) {
			description += str[i] + " ";
		}
		return description;
	}
	
	public static String getAlias(String str) {
		str = StringHelper.replaceVietnamese(str);
		str = StringHelper.replace(str);
		return str;
	}
	
	public static String replace(String str) {
		str = str.replaceAll("[\\W]+", "-");
		str = str.replaceAll("^-", "");
		str = str.replaceAll("-$", "");
		str = str.toLowerCase();
		return str;
	}

	public static String replaceVietnamese(String str) {
		String[] aArray = {"Ă¡ÂºÂ¥", "Ă¡ÂºÂ§", "Ă¡ÂºÂ©", "Ă¡ÂºÂ«", "Ă¡ÂºÂ­", "Ă¡ÂºÂ¤", "Ă¡ÂºÂ¦", "Ă¡ÂºÂ¨", "Ă¡ÂºÂª", "Ă¡ÂºÂ¬", "Ă¡ÂºÂ¯", "Ă¡ÂºÂ±", "Ă¡ÂºÂ³", "Ă¡ÂºÂµ", "Ă¡ÂºÂ·",
				"Ă¡ÂºÂ®", "Ă¡ÂºÂ°", "Ă¡ÂºÂ²", "Ă¡ÂºÂ´", "Ă¡ÂºÂ¶", "Ä‚Â¡", "Ä‚Â ", "Ă¡ÂºÂ£", "Ä‚Â£", "Ă¡ÂºÂ¡", "Ä‚Â¢", "Ă„Æ’",
				"Ä‚ï¿½", "Ä‚â‚¬", "Ă¡ÂºÂ¢", "Ä‚Æ’", "Ă¡ÂºÂ ", "Ä‚â€�", "Ă„â€�" };
		String[] eArray = { "Ă¡ÂºÂ¿", "Ă¡Â»ï¿½", "Ă¡Â»Æ’", "Ă¡Â»â€¦", "Ă¡Â»â€¡", "Ă¡ÂºÂ¾", "Ă¡Â»â‚¬", "Ă¡Â»â€�", "Ă¡Â»â€�", "Ă¡Â»â€ ",
				"Ä‚Â©", "Ä‚Â¨", "Ă¡ÂºÂ»", "Ă¡ÂºÂ½", "Ă¡ÂºÂ¹", "Ä‚Âª", "Ä‚â€°", "Ä‚Ë†", "Ă¡ÂºÂº", "Ă¡ÂºÂ¼", "Ă¡ÂºÂ¸", "Ä‚ï¿½" };
		String[] iArray = { "Ä‚Â­", "Ä‚Â¬", "Ă¡Â»â€°", "Ă„Â©", "Ă¡Â»â€¹", "Ä‚ï¿½", "Ä‚Å’", "Ă¡Â»Ë†", "Ă„Â¨", "Ă¡Â»ï¿½" };
		String[] oArray = { "Ă¡Â»â€˜", "Ă¡Â»â€œ", "Ă¡Â»â€¢", "Ă¡Â»â€”", "Ă¡Â»â„¢", "Ă¡Â»ï¿½", "Ă¡Â»â€™", "Ă¡Â»â€�", "Ä‚â€�", "Ă¡Â»Ëœ",
				"Ă¡Â»â€º", "Ă¡Â»ï¿½", "Ă¡Â»Å¸", "Ă¡Â»Â¡", "Ă¡Â»Â£", "Ă¡Â»ï¿½", "Ă¡Â»Å“", "Ă¡Â»ï¿½", "Ă¡Â»Â ", "Ă¡Â»Â¢", "Ä‚Â³", "Ä‚Â²",
				"Ă¡Â»ï¿½", "Ä‚Âµ", "Ă¡Â»ï¿½", "Ä‚Â´", "Ă†Â¡", "Ä‚â€œ", "Ä‚â€™", "Ă¡Â»ï¿½", "Ä‚â€¢", "Ă¡Â»Å’", "Ä‚â€�", "Ă†Â " };
		String[] uArray = { "Ă¡Â»Â©", "Ă¡Â»Â«", "Ă¡Â»Â­", "Ă¡Â»Â¯", "Ă¡Â»Â±", "Ă¡Â»Â¨", "Ă¡Â»Âª", "Ă¡Â»Â¬", "Ă¡Â»Â®", "Ă¡Â»Â°",
				"Ä‚Âº", "Ä‚Â¹", "Ă¡Â»Â§", "Ă…Â©", "Ă¡Â»Â¥", "Ă†Â°", "Ä‚ï¿½", "Ä‚â„¢", "Ă¡Â»Â¦", "Ă…Â¨", "Ă¡Â»Â¤", "Ă†Â¯" };
		String[] yArray = { "Ä‚Â½", "Ă¡Â»Â³", "Ă¡Â»Â·", "Ă¡Â»Â¹", "Ă¡Â»Âµ", "Ä‚ï¿½", "Ă¡Â»Â²", "Ă¡Â»Â¶", "Ă¡Â»Â¸", "Ă¡Â»Â´" };
		String[] dArray = { "Ă„â€˜", "Ă„ï¿½" };
		for (String item : aArray) {
			str = str.replaceAll(item, "a");
		}
		for (String item : eArray) {
			str = str.replaceAll(item, "e");
		}
		for (String item : iArray) {
			str = str.replaceAll(item, "i");
		}
		for (String item : oArray) {
			str = str.replaceAll(item, "o");
		}
		for (String item : uArray) {
			str = str.replaceAll(item, "u");
		}
		for (String item : yArray) {
			str = str.replaceAll(item, "y");
		}
		for (String item : dArray) {
			str = str.replaceAll(item, "d");
		}
		str = str.replaceAll("[\\W]+", " ");
		str = str.replaceAll("^-", "");
		str = str.replaceAll("-$", "");
		str = str.toLowerCase();
		return str;

	}

	public static String tag(String str) {
		str = str.replaceAll("\\#", "Sharp");
		str = str.replaceAll("\\+", "Plus");
		str = str.replaceAll("[^.\\w]+", "-");
		str = str.replaceAll("^-", "");
		str = str.replaceAll("-$", "");
		str = str.toLowerCase();
		return str;
	}

	public static String remove(String str) {
		str = str.replaceAll("[\'\"]+", "&quot;");
		return str;
	}

	public static boolean StringIsNullOrEmpty(String string) {
		if (string == null || string.equals("")) {
			return true;
		}
		return false;
	}
	
	public static ArrayList<String> findString(String regex, String input) {
		ArrayList<String> result = new ArrayList<String>();
		Pattern p = Pattern.compile(regex);
	    Matcher m = p.matcher(input); // get a matcher object
	     while(m.find()) {
	       result.add(input.substring(m.start(), m.end()));
	    }
		return result;
	}
	
	public static String html2text(String html) {
		return Jsoup.parse(html).text();
	}
	
	public static String text2UTF8(String str) {
		byte[] utf8bytes = str.getBytes();
		return new String(utf8bytes,Charset.forName("UTF-8"));
	}
	
	public static String arrayToString(String[] a, String separator) {
	    if (a == null || separator == null) {
	        return null;
	    }
	    StringBuilder result = new StringBuilder();
	    if (a.length > 0) {
	        result.append(a[0]);
	        for (int i=1; i < a.length; i++) {
	            result.append(separator);
	            result.append(a[i]);
	        }
	    }
	    return result.toString();
   }
	
  public static String arrayListToString(ArrayList<String> a, String separator) {
	  StringBuilder result = new StringBuilder();
	  if (a.size() > 0) {
		  result.append(a.get(0));
		  for (int i = 1; i < a.size(); i++) {
			  result.append(separator);
	          result.append(a.get(i));
		  }
	  }
	  return result.toString();
  }
  
  public static String listToString(List<String> str, String separator) {
	  StringBuilder result = new StringBuilder();
	  if (str.size() > 0) {
		  result.append(str.get(0));
		  for (int i = 1; i < str.size(); i++) {
			  result.append(separator);
	          result.append(str.get(i));
		  }
	  }
	  return result.toString();
  }
  
  public static String translate(String string, String language) throws IOException {
		string = URLEncoder.encode(string.replaceAll("[\\']{1}", "\\\'").replaceAll("[\\\"]{1}", "\\\""), "UTF-8");
		URL url = new URL("http://translate.google.com/?hl=en&tab=TT");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestMethod("POST");
		connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.21) Gecko/20110830 AlexaToolbar/alxf-2.14 AlexaToolbar/pXVUnvuf-1.2 Firefox/3.6.21");
		connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		connection.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
		connection.setRequestProperty("Accept-Charset", "       ISO-8859-1,utf-8;q=0.7,*;q=0.7");
		connection.setRequestProperty("Connection", "keep-alive");
		connection.setRequestProperty("Keep-Alive", "115");
		connection
				.setRequestProperty(
						"Cookie",
						"PREF=ID=987bb7a56b1cc7bc:U=691fa246d56f502e:FF=0:TM=1314876638:LM=1314876681:S=yBXzqp_WQq9ykX-j; NID=50=nfNXg7ymSSsfdzMnkEuo7t1GCgIEwcK5xmpFhu1mQWwvNI5nFHLZpRsy_1XnaoKrdj9hnz7za9-M2OIO99phfFSTmXln-xCvqzJaRWHsN0EQKgpmkvgUDTWPVF4I4c9L; SID=DQAAALcAAADhqr-J8Ls3CKhmbRjwTMMP1DjmIvR8qBFxv99saTaFFgoRsVf18W4p_BTocYoxYNMvsvh9sfjMj7KqLyd_s9Y0lwYY_Rrljd7t5IpKBTWWnsv9VSJ_qelH943zV8YIT3uuIdJbHhFlCnVEu_YealZoldWjf4VirYR0PIrr0i4_JU2JCHRmpyW0ACt3KcyLkukJlGDyT5yC5js3CBSTAhnWSylBpMWPWyWJzqXe2BQFcdfuU_qo00pAR-uEcMQ437M; HSID=A9Z-j3CKhzDEykAES");
		connection.setRequestProperty("Cache-Control", "max-age=0");
		OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
		writer.write("text=" + string);
		writer.write("&eotf=1");
		writer.write("&hl=vi");
		writer.write("&ie=UTF-8");
		writer.write("&js=n");
		writer.write("&layout=2");
		writer.write("&prev=_t");
		writer.write("&sl=en");
		writer.write("&tl=" + language);
		writer.close();
		if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
			String content = "";
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
			while (1 == 1) {
				String str = reader.readLine();
				if (str == null)
					break;
				content += str;
			}
			Document doc = Jsoup.parse(content);
			string = doc.select("#result_box").text().replaceAll("<[ ]*/[ ]+", "</");
		}
		return string;
	}
}
